<?php
namespace Models;

require_once('Base.php');
require_once('\Common\Validator.php');
require_once('\Models\Database.php');
require_once('\Models\ImageCatalog.php');
require_once('\Models\Album.php');
require_once('\Common\DBTables.php');
require_once('\Common\Strings.php');
require_once('\Common\Validator.php');

class ManageAlbumsModel
{
	private $_db = null;
	private $_dbt = null;
	public $errors;
	
	public function __construct(\Models\Database $db)
	{
		$this->_db = $db;
		$this->_dbt = new \Common\DBTables();
		$this->errors = array();
	}
	
	/**
	 * Skapa ett fotoalbum
	 * @param $userId int
	 * @param $albumTitle string
	 * @param $albumYear int
	 * @param $albumDescription string
	 * @return $insertId int
	 */
	public function createAlbum($userId, $albumTitle, $albumYear, $albumDescription)
	{
		$output = array();
		$insertId = 0;
		
		if(!\Common\Validator::validateString($albumTitle))
			$this->errors[] = \Common\Strings::VALIDATION_ALBUMTITLE_INCORRECT;
		
		if(!\Common\Validator::validateNumber($albumYear))
			$this->errors[] = \Common\Strings::VALIDATION_YEAR_INCORRECT;
		
		// Kollar att användarid:t finns i DB
		if(!$this->_db->alreadyExists($this->_dbt->userTable, $this->_dbt->userIdField, $userId))
			$this->errors[] = \Common\Strings::VALIDATION_USER_MISSING;
		
		// Ta bort HTML och JS från strängar		
		$at = \Common\Validator::filterString($albumTitle, 1);
		$at = \Common\Validator::filterString($at, 0);
		$ad = \Common\Validator::filterString($albumDescription, 1);
		$ad = \Common\Validator::filterString($ad, 0);
		
		// Exekvera sql om inga fel uppstått
		if(count($this->errors) == 0)
		{
			
			$sql = "INSERT INTO ".$this->_dbt->albumTable.
			"(".
			$this->_dbt->userIdField.",".
			$this->_dbt->albumTitleField.",".
			$this->_dbt->albumYearField.",".
			$this->_dbt->albumDescriptionField.
			") 
			VALUES (?,?,?,?)";
			
			$statement = $this->_db->Prepare($sql);
			
			$statement->bind_param("isis", $userId, $at, $albumYear, $ad);
			
			$insertId = $this->_db->Insert($statement);
		}
		
		return $insertId;
	}

	/**
	 * Editera ett fotoalbum
	 * @param $albumId int
	 * @param $albumTitle string
	 * @param $albumYear int
	 * @param $albumDescription string
	 * @return bool
	 */
	public function updateAlbum(\Models\Album $album)
	{
		$this->errors = array();
		
		if(!\Common\Validator::validateString($album->Title()))
			$this->errors[] = \Common\Strings::VALIDATION_ALBUMTITLE_INCORRECT;
		
		if(!\Common\Validator::validateNumber($album->Year()))
			$this->errors[] = \Common\Strings::VALIDATION_YEAR_INCORRECT;
		
		// Kollar att albumId:t finns i DB
		if(!$this->_db->alreadyExists($this->_dbt->albumTable, $this->_dbt->albumIdField, $album->AlbumId()))
			$this->errors[] = \Common\String::DB_ALBUM_MISSING;
		
		// Exekvera sql om inga fel uppstått
		if(count($this->errors) == 0)
		{
			$sql = "UPDATE ".$this->_dbt->albumTable." SET ".
			$this->_dbt->userIdField."=? ,".
			$this->_dbt->albumTitleField."=? ,".
			$this->_dbt->albumYearField."=? ,".
			$this->_dbt->albumDescriptionField."=? 
			WHERE ".$this->_dbt->albumIdField."=?";
		
			$statement = $this->_db->Prepare($sql);
			
			// Endast variabler får bindas, ej returvärden
			$uid = $album->UserId();
			$ay = $album->Year();
			$at = $album->Title();
			$ad = $album->Description();
			$aid = $album->AlbumId();
			
			// Ta bort HTML och JS från strängar		
			$at = \Common\Validator::filterString($at, 1);
			$at = \Common\Validator::filterString($at, 0);
			$ad = \Common\Validator::filterString($ad, 1);
			$ad = \Common\Validator::filterString($ad, 0);
			
			$statement->bind_param("isisi", $uid, $at, $ay, $ad, $aid);
			
			if($this->_db->Update($statement))
				return true;
		}
		return false;
	}

	/**
	 * Ta bort ett fotoalbum
	 * @param $albumId int
	 * @return bool
	 */
	public function deleteAlbum($albumId)
	{
		$this->errors = array();
		
		// Kollar att användarid:t finns i DB
		if(!$this->_db->alreadyExists($this->_dbt->albumTable, $this->_dbt->albumIdField, $albumId))
			$this->errors[] = \Common\Strings::DB_ALBUM_MISSING;
		else
		{
			// Hämtar utvalda bilder innan borttagning
			$ic = new \Models\ImageCatalog();
			$images = $ic->getImages($this->_db, $albumId);
				
			$sql = "DELETE FROM ".$this->_dbt->albumTable." WHERE ".$this->_dbt->albumIdField."=?";
			
			$statement = $this->_db->Prepare($sql);
			
			$statement->bind_param("i", $albumId);
			
			if($this->_db->Delete($statement))
			{
				if($images != false)
				{
					foreach ($images->get() as $image)
					{
						$thumbPath = ABSPATH . "/" . $image->ThumbUrl();
						$imagePath = ABSPATH . "/" . $image->ImageUrl();
						
						if(!unlink($thumbPath))
							$this->errors[] = \Common\Strings::DB_IMAGE_DELETE_FAIL . $thumbPath;
						
						if(!unlink($imagePath))
							$this->errors[] = \Common\Strings::DB_IMAGE_DELETE_FAIL . $imagePath;
					}
				}
				if(count($this->errors)==0)
					return true;
			}
		}
		return false;
	}
	
	/**
	 * Lägg till bild i album
	 */
	public function addImage(\Models\Image $image)
	{
		$this->errors = array();
		$insertId = 0;
		
		// Kollar att albumId finns i DB
		if(!$this->_db->alreadyExists($this->_dbt->albumTable, $this->_dbt->albumIdField, $image->AlbumId()))
			$this->errors[] = \Common\String::DB_ALBUM_MISSING;
		
		if(!\Common\Validator::validateString($image->ImageUrl()))
			$this->errors[] = \Common\Strings::VALIDATION_IMAGE_URL_INCORRECT;
		
		if(!\Common\Validator::validateString($image->ThumbUrl()))
			$this->errors[] = \Common\Strings::VALIDATION_THUMB_URL_INCORRECT;
		
		// Exekvera sql om inga fel uppstått
		if(count($this->errors) == 0)
		{
			$sql = "INSERT INTO ".$this->_dbt->imageTable.
			"(".
			$this->_dbt->albumIdField.",".
			$this->_dbt->albumDescriptionField.",".
			$this->_dbt->imageUrlField.",".
			$this->_dbt->thumbUrlField.
			") 
			VALUES (?,?,?,?)";
			
			$statement = $this->_db->Prepare($sql);
			
			$aid = $image->AlbumId();
			$des = $image->Description();
			$iurl = $image->ImageUrl();
			$turl = $image->ThumbUrl();
			
			// Ta bort HTML och JS
			$des = \Common\Validator::filterString($des, 1);
			$des = \Common\Validator::filterString($des, 0);
			
			$statement->bind_param("isss", $aid, $des, $iurl, $turl);
			
			$insertId = $this->_db->Insert($statement);
		}
		return $insertId;
	}

	/**
	 * Uppdaterar ett albums bilder
	 * @return $output array - felmeddelanden (om några)
	 */
	public function updateImages(\Models\ImageArray $images)
	{
		$this->errors = array();
		
		// Kollar att bilderna finns i DB
		foreach ($images->get() as $image)
		{
			if(!$this->_db->alreadyExists($this->_dbt->imageTable, $this->_dbt->imageIdField, $image->ImageId()))
				$this->errors[] = \Common\Strings::DB_IMAGE_MISSING;
			
			if(!\Common\Validator::validateString($image->ImageUrl()))
				$this->errors[] = \Common\Strings::VALIDATION_IMAGE_URL_INCORRECT;
			
			if(!\Common\Validator::validateString($image->ThumbUrl()))
				$this->errors[] = \Common\Strings::VALIDATION_THUMB_URL_INCORRECT;
		}

		// Exekvera sql om inga fel uppstått
		if(count($this->errors) == 0)
		{
			foreach ($images->get() as $image)
			{
				$sql = "UPDATE ".$this->_dbt->imageTable." SET ".
				$this->_dbt->albumIdField."=? ,".
				$this->_dbt->imageDescriptionField."=? ,".
				$this->_dbt->imageUrlField."=? ,".
				$this->_dbt->thumbUrlField."=? 
				WHERE ".$this->_dbt->imageIdField."=?";
				
				$statement = $this->_db->Prepare($sql);
				
				$aid = $image->AlbumId();
				$des = $image->Description();
				$iurl = $image->ImageUrl();
				$turl = $image->ThumbUrl();
				$iid = $image->ImageId();
				
				// Ta bort HTML och JS
				$des = \Common\Validator::filterString($des, 1);
				$des = \Common\Validator::filterString($des, 0);
				
				$statement->bind_param("isssi", $aid, $des, $iurl, $turl, $iid);
				
				if(!$this->_db->Update($statement))
					$this->errors[] = \Common\Strings::DB_IMAGE_UPDATE_FAIL;
			}
		}
		
		if(count($this->errors) == 0)
			return true;
		else
			return false;
	}

	/**
	 * Tar bort specifika bilder från ett album
	 * @param $imagesToDelete array
	 * @return $output - felmeddelanden (om några)
	 */
	public function deleteImages($imagesToDelete, $albumId)
	{
		$this->errors = array();
		
		// Kollar att bilderna finns i DB
		for ($i=0; $i<count($imagesToDelete); $i++)
		{
			if(!$this->_db->alreadyExists($this->_dbt->imageTable, $this->_dbt->imageIdField, $imagesToDelete[$i]))
				$this->errors[] = \Common\Strings::DB_IMAGE_MISSING;
		}

		// Exekvera sql om inga fel uppstått
		if(count($this->errors) == 0)
		{
			$ic = new \Models\ImageCatalog();
			
			// Hämtar utvalda bilder som en ImageArray
			$selectedImages = $ic->getImages($this->_db, $albumId, $imagesToDelete);
			
			// Skriv över som array
			$selectedImages = $selectedImages->get();
			
			for ($i=0; $i<count($imagesToDelete); $i++)
			{
				$sql = "DELETE FROM ".$this->_dbt->imageTable."
				WHERE ".$this->_dbt->imageIdField."=?";
				
				$statement = $this->_db->Prepare($sql);
				$statement->bind_param("i", $imagesToDelete[$i]);
				
				// Ta bort filer på disk om borttagning i DB lyckas
				if($this->_db->Delete($statement))
				{
					$thumbPath = ABSPATH . "/" . $selectedImages[$i]->ThumbUrl();
					$imagePath = ABSPATH . "/" . $selectedImages[$i]->ImageUrl();
					
					if(!unlink($thumbPath))
						$output[] = \Common\Strings::DB_IMAGE_DELETE_FAIL . $thumbPath;
					
					if(!unlink($imagePath))
						$output[] = \Common\Strings::DB_IMAGE_DELETE_FAIL . $imagePath;
				}
			}
		}
		
		if(count($this->errors)==0)
			return true;
		else
			return false;
	}
}

?>